# 界面逻辑文件

import json
import sys
import requests
from PyQt5 import QtWidgets
from PyQt5.QtCore import QUrl, QByteArray, QThread, pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineProfile
from GUI.UI_MainWindow import Ui_MainWindow, Ui_OptionWindow
from Spider.Spider import ZTCSpider
from rely.functional_module import logger
from rely.dataDase_action import GetMCode



class LogicWindow(QtWidgets.QMainWindow, Ui_MainWindow):  # logic:逻辑  业务逻辑代码
    def __init__(self):
        super(LogicWindow, self).__init__()
        self.setupUi(self)
        self.browser = QWebEngineView()
        # 绑定cookie被添加的信号槽
        QWebEngineProfile.defaultProfile().cookieStore().cookieAdded.connect(self.onCookieAdd)
        self.browser.loadFinished.connect(self.onLoadFinished)  # TODO 登录完成
        self.setWindowIcon(QIcon('../rely/icons/ztc.ico'))

        logger.debug("主窗口创建完成")
        self.DomainCookies = {}  # 存放domain的key-value
        self.PathCookies = {}  # 存放domain+path的key-value
        self.plan_info_dic = {}  # 保存标准计划信息，key：计划名，val：计划id


    def onCookieAdd(self, cookie):  # cookies 添加时触发操作
        """
        :param cookie: QNetworkCookie
        """
        domain = cookie.domain()
        path = cookie.path()
        name = cookie.name().data().decode()
        value = cookie.value().data().decode()
        if domain in self.DomainCookies:
            _cookie = self.DomainCookies[domain]
            _cookie[name] = value
        else:
            self.DomainCookies[domain] = {name: value}
        domain_path = domain + path
        if domain_path in self.PathCookies:
            _cookie = self.PathCookies[domain_path]
            _cookie[name] = value
        else:
            self.PathCookies[domain_path] = {name: value}

    def bytestostr(self, data):
        if isinstance(data, str):
            return data
        if isinstance(data, QByteArray):
            data = data.data()
        if isinstance(data, bytes):
            data = data.decode(errors='ignore')
        else:
            data = str(data)
        return data

    def onLoadFinished(self):
        if "subway.simba.taobao.com" in self.DomainCookies:  # 判断是否登录成功
            dict_1 = self.getDomainCookies(".taobao.com")
            dict_2 = self.getDomainCookies("subway.simba.taobao.com")
            self.cookies_ = ""
            for i1 in dict_1:
                self.cookies_ += (i1 + "=" + dict_1[i1] + "; ")
            # for i2 in dict_2:
            #     self.cookies_ += (i2 + "=" + dict_2[i2] + "; ")
            print('cookies:', self.cookies_)
            shop_name = self.get_data()
            print(75,self.plan_info_dic)
            print(76,shop_name)
            if shop_name not in GetMCode().query_shop_names():
                logger.info('店铺名未注册')
                QtWidgets.QMessageBox.information(self, "提示 ^_^", "该店铺名 暂时还没注册\n请联系管理员注册", QtWidgets.QMessageBox.Yes)
                sys.exit()
            self.show_option(self.plan_info_dic)

    def getDomainCookies(self, domain):
        return self.DomainCookies.get(domain, {})

    def getPathCookies(self, dpath):
        return self.PathCookies.get(dpath, {})

    def login_page(self):
        """
        槽函数
        :return:
        """
        logger.info("调用槽函数，展示登录页")
        self.browser.load(QUrl("https://zhitongche.taobao.com/"))  # 加载外部页面，调用
        self.setCentralWidget(self.browser)  # 将浏览器引擎 设置为主窗口小部件

    def show_option(self, plan_info_dic):  # 展示选项
        self.option_ui = Ui_OptionWindow()
        self.option_ui.setupUi(self,plan_info_dic)
        logger.info('选项界面已展示')


    def get_data(self):
        """
        调用爬虫 获取数据
        :return:
        """
        self.spider = ZTCSpider(self.cookies_)
        shop_name = self.spider.get_username()
        self.plan_info_dic = self.spider.get_plan_info_dic()
        logger.debug('标准计划信息：%s' % self.plan_info_dic)
        return shop_name


    def get_option_info(self):
        radioButton_isChecked_list = []  # 待处理计划元素列表
        for radioButton in self.option_ui.radioButton_list:  # 遍历所有的单选框
            if radioButton.isChecked():
                radioButton_isChecked_list.append(radioButton)
        if len(radioButton_isChecked_list) == 0:
            QtWidgets.QMessageBox.information(self, "提示", "请勾选需要抓取的计划", QtWidgets.QMessageBox.Yes)

        logger.info('待处理计划元素列表：', radioButton_isChecked_list)
        return radioButton_isChecked_list



    def delete_data(self):
        """"""
        # 删除计划按钮对应的 槽函数
        logger.info("===调用删除槽函数===")
        radioButton_isChecked_list = self.get_option_info()
        if len(radioButton_isChecked_list) == 0:
            logger.info("没选中计划，退出槽函数")
            return
        # 创建线程
        self.spider_thread = SpiderThread(radioButton_isChecked_list,self.spider,self.plan_info_dic,self.spider.headers)
        # 注册信号处理函数
        self.spider_thread._signal.connect(self.chuli)
        # 启动线程
        self.spider_thread.start()

    def chuli(self, s):
        print("信号来了", s)
        if s["delete_status"] == "200":
            logger.info('删除状态:%s' % s["delete_status"])
            radioButton = s['delete_radioButton']
            self.option_ui.radioButton_list.remove(radioButton)
            radioButton.deleteLater()  # 删除单选框
            logger.info('单选框已删除')
            logger.info('计划删除成功')
            QtWidgets.QMessageBox.information(self, "提示", "计划删除成功", QtWidgets.QMessageBox.Yes)
        else:
            # 处理完成，弹窗提示
            logger.info('计划删除失败')
            QtWidgets.QMessageBox.information(self, "提示", "计划删除失败", QtWidgets.QMessageBox.Yes)


class SpiderThread(QThread):
    # 定义信号,定义参数为str类型
    _signal = pyqtSignal(dict)

    def __init__(self,radioButton_isChecked_list, spider, plan_info_dic, headers):
        super(SpiderThread, self).__init__()
        self.radioButton_isChecked_list = radioButton_isChecked_list
        self.plan_info_dic = plan_info_dic
        self.spider = spider
        self.headers = headers

    def __del__(self):
        self.wait()

    def run(self):
        print("1、处理删除操作")
        plan_title = self.radioButton_isChecked_list[0].text()
        plan_id = self.plan_info_dic[plan_title]
        delete_url = "https://subway.simba.taobao.com/campaign/delete.htm"
        delete_data = {
            "campaignIds": "[{}]".format(plan_id),
            "sla": "json",
            "isAjaxRequest": "true",
            "token": "24815c8e",
            "_referer": "/manage/campaign/index?selectedCampaignType=8"
        }
        res_ = requests.post(delete_url, data=delete_data, headers=self.headers)
        print(res_.text)
        delete_status = json.loads(res_.text)["code"]
        #  code:200  删除成功
        #  code:600  系统异常，请尝试重新提交或者刷新页面
        self._signal.emit({"delete_status":delete_status, "delete_radioButton":self.radioButton_isChecked_list[0]})  # 发出信号


if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = LogicWindow()
    win.show()
    sys.exit(app.exec_())
